package org.mog.user.websocket;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import vo.UserLoginVO;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/ws/{sid}")
@Slf4j
@Component
public class WebSocketServer {
    private static int onlineCount = 0;
    private static Map<String, WebSocketServer> clients = new ConcurrentHashMap<>();
    private Session session;
    private String sid;

    @OnOpen
    public void onOpen(@PathParam("sid") String sid, Session session) {
        this.sid = sid;
        this.session = session;
        WebSocketServer.onlineCount++;
        clients.put(sid, this);
        log.info("连接到客户端：{}", sid);
    }

    @OnClose
    public void onClose() {
        clients.remove(sid);
        WebSocketServer.onlineCount--;
        log.info("断开连接：{}", sid);
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("收到客户端消息：{}", message);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("WebSocket发生错误：{}", throwable.getMessage());
    }

    public static void sent2Client(UserLoginVO userLoginVO, String sid) {
        WebSocketServer item = clients.get(sid);
        item.session.getAsyncRemote().sendText(JSONUtil.toJsonStr(userLoginVO));
    }
}

